package com.atguli.gulimall.product.exception;

import com.atguli.common.enums.BizCodeEnum;
import com.atguli.common.exception.RRException;
import com.atguli.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * Controller
 *
 * @author xionghw0982
 * @date 2021-06-22 15:14
 */

/**
    集中处理所有异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.atguli.gulimall.product.controller")
public class ProductException {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现异常{}，异常类型：{}",e.getMessage(),e.getClass());
        final BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach((item) -> {
            // 获取错误提示
            final String message = item.getDefaultMessage();
            // 获取错误字段
            final String field = item.getField();
            map.put(field, message);
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMessage()).put("data",map);
    }

    @ExceptionHandler(value = RRException.class)
    public R handleValidException(RRException e) {
        log.error(e.getLocalizedMessage());
        return R.error(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleValidException(Throwable e) {
        log.error(e.getLocalizedMessage());
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(),BizCodeEnum.UNKNOWN_EXCEPTION.getMessage());
    }
}
